package com.lyy.config;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import com.lyy.annotation.Desensitize;
import com.lyy.entity.Student;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @author Liangyaoyun
 */
@Log4j2
@Aspect
@Component
public class ServiceAspect {


    @SneakyThrows
    @Around("execution(* com.lyy.service.impl..*.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint pjp) {
        Object[] args=pjp.getArgs();
        //前置通知：检查参数是否为空
        if (ObjectUtil.hasNull(args)){
            throw new RuntimeException("必要参数为空");
        }

        //调用业务方法
        Object returnValue=pjp.proceed(pjp.getArgs());
        //后置通知：记录日志
        log.info("调用了{}类中的{}方法",
                pjp.getTarget(),
                pjp.getSignature());

        // 返回通知: 数据脱敏
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        // 若业务方法上添加了 `@Desensitize` 注解，才会执行脱敏操作
        if(methodSignature.getMethod().isAnnotationPresent(Desensitize.class)){
            // 若业务方法的返回值为 Student 才会执行脱敏操作
            if (returnValue instanceof Student) {
                Student student = (Student) returnValue;
                student.setPhone(DesensitizedUtil.mobilePhone(student.getPhone()));
            }
        }
        return returnValue;
    }
}
